package com.itheima.project.face.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.project.basic.ResponseWrap;
import com.itheima.project.enums.BrandEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.face.BrandFace;
import com.itheima.project.feign.FileFeign;
import com.itheima.project.pojo.Brand;
import com.itheima.project.service.BrandService;
import com.itheima.project.utils.BeanConv;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.utils.ExceptionsUtil;
import com.itheima.project.vo.BrandVo;
import com.itheima.project.vo.file.FileVo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName BrandFaceImpl
 * @Description 品牌face实现类
 */
@Component
@Slf4j
public class BrandFaceImpl implements BrandFace {
    @Autowired
    BrandService brandService;
    @Autowired
    FileFeign fileFeign;


    @Override
    public Page<BrandVo> findBrandVoPage(BrandVo brandVo, int pageNum, int pageSize) throws ProjectException {
        try {
            //查询Page<Brand>品牌分页
            Page<Brand> page = brandService.findBrandVoPage(brandVo, pageNum, pageSize);
            //转化Page<Brand>为Page<BrandVo>
            Page<BrandVo> pageVo = BeanConv.toPage(page, BrandVo.class);
            //转换List<Brand>为 List<BrandVo>
            List<BrandVo> brandVoList = pageVo.getRecords();
            //处理附件
            if (!EmptyUtil.isNullOrEmpty(brandVoList)) {
                brandVoList.forEach(n -> {
                    ResponseWrap<List<FileVo>> responseWrap = fileFeign.findFileVoByBusinessId(FileVo.builder().businessId(n.getId()).build());
                    if (!EmptyUtil.isNullOrEmpty(responseWrap.getDatas())) {
                        n.setFileVo(responseWrap.getDatas().get(0));
                    } else {
                        n.setFileVo(FileVo.builder().build());
                    }
                });
            }
            //返回结果
            pageVo.setRecords(brandVoList);
            return pageVo;
        } catch (Exception e) {
            log.error("查询品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.PAGE_FAIL);
        }

    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public BrandVo createBrand(BrandVo brandVo) throws ProjectException {
        try {
            Brand brand = brandService.createBrand(brandVo);
            BrandVo brandVoResult = BeanConv.toBean(brand, BrandVo.class);
            //绑定附件
            if (!EmptyUtil.isNullOrEmpty(brandVoResult)){
                fileFeign.bindBusinessId(FileVo.builder()
                        .businessId(brandVoResult.getId())
                        .id(brandVo.getFileVo()
                                .getId())
                        .build());
                //回显
                brandVoResult.setFileVo(FileVo.builder()
                        .pathUrl(brandVo.getFileVo().getPathUrl())
                        .businessId(brandVoResult.getId())
                        .id(brandVo.getFileVo().getId()).build());
            }

            return brandVoResult;
        } catch (Exception e) {
            log.error("保存品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.CREATE_FAIL);
        }
//        try {
//            // 创建品牌
//            Brand brand = brandService.createBrand(brandVo);
//            // VO转换
//            BrandVo result = BeanConv.toBean(brand, BrandVo.class);
//            // 绑定附件
//            if (!EmptyUtil.isNullOrEmpty(result)) {
//                // 前端传入的FileVO
//                FileVo fileVo = brandVo.getFileVo();
//                // 设置关联业务id
//                fileVo.setBusinessId(result.getId());
//                // 绑定附件
//                fileFeign.bindBusinessId(fileVo);
//                // 用于回显
//                result.setFileVo(fileVo);
//            }
//            return result;
//        } catch (Exception e) {
//            log.error("保存品牌出现异常 : {}",ExceptionsUtil.getStackTraceAsString(e));
//            throw new ProjectException(BrandEnum.CREATE_FAIL);
//        }
    }
    @Override
    public Boolean updateBrand(BrandVo brandVo) throws ProjectException {

        try {
            // 修改品牌
            Boolean flag = brandService.updateBrand(brandVo);
            if (!flag) throw new ProjectException(BrandEnum.UPDATE_FAIL);
            // 移除业务原图片，并绑定新的图片到业务上
            fileFeign.replaceBindBusinessId(FileVo.builder()
                    .businessId(brandVo.getId())
                    .id(brandVo.getFileVo().getId())
                    .build());
            return flag;
        } catch (ProjectException e) {
            log.error("修改品牌出现异常 :{}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.UPDATE_FAIL);
        }
    }
    @Override
    public Boolean deleteBrand(List<Long> checkedIds) throws ProjectException {
        // 删除勾选的品牌
        try {
            Boolean flag = brandService.deleteBrand(checkedIds);
            if (flag){
                // 删除品牌相关的文件
                for (Long checkedId : checkedIds) {
                    fileFeign.deleteFileVoByBusinessId(FileVo.builder().businessId(checkedId).build());
                }
            }
            return flag;
        } catch (Exception e) {
            log.error("删除品牌出现异常 : {}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.DELETE_FAIL);
        }
    }
    @Override
    public BrandVo findBrandByBrandId(Long brandId) throws ProjectException {
        try {
            // 查询品牌
            Brand brand = brandService.getById(brandId);
            return BeanConv.toBean(brand, BrandVo.class);
        } catch (Exception e) {
            log.error("查询品牌失败 : {}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.SELECT_BRAND_FAIL);
        }
    }
    @Override
    public List<BrandVo> findBrandVoList() throws ProjectException {
        try {
            return BeanConv.toBeanList(brandService.findBrandVoList(),BrandVo.class);
        } catch (Exception e) {
            log.error("查询品牌列表失败 : {}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.SELECT_BRAND_FAIL);
        }
    }
}
